<?php

class UnionFace extends FaceBase
{
	private $nohf = ['bind', 'bindadd'];
	private $mysql = null;
	private $api = null;

	public function __construct()
	{
		parent::__construct();
		if(!in_array(N_ACTION,$this->nohf)){
			n_mod('skin')->header();
		}
		$this->mysql = n_api('mysql')->cname('weixin');
		$this->api = n_api('union');
	}

	public function index(){
		
		
		$this->_html("index");
	}


	public function myunion()
	{
		$ppid = $_SESSION['ppid'];
		$unionInfo = $this->api->getUnionInfoByPpid($ppid);
		foreach ($unionInfo as $value) {
			$wxids[] = $value['wxid'];
		}
		$wxDetails = n_api('weixin')->getWxDetail($wxids);
		$data = [];
		foreach ($wxDetails as $value) {
			if ($value['flag'] == 1)
				$data[] = $value;
			else {
				$value['auth'] = '正在同步...';
				$value['face_wxid'] = 'wait_8888';
				$data[] = $value;
			}
		}
		$this->_html('myunion', $data);
	}

	public function bind()
	{
		$time = mt_rand(0, 100) . microtime(true) . mt_rand(100, 400);
		$data['md5'] = md5($time);
		$groups = n_api('weixin')->getCategories();
		foreach($groups as $key=>$val){
			$data['groups'][$val['first_category']][$val['id']] = $val;
		}
		$_SESSION['md5'] = $data['md5'];
		$this->_html('bind', $data);
	}

	public function bindAdd()
	{
		$param = $this->param('
			url:char:empty,
			group:char:empty
		');

		$url = $param['url'];
		$groupId = $param['group'];
		$weixin = n_api('weixin');

		$urlQuery = parse_url($url, PHP_URL_QUERY);
		parse_str($urlQuery);

		$rs = $weixin->getArticleByUrl($url);

		$md5 = $_SESSION['md5'];
		unset($_SESSION['md5']);
		if (!strpos($rs, $md5))
			exit('not found');
		$weixinInfo = $weixin->getArticleWeixinInfo($rs);

		$wxid = $weixinInfo['wxid'];

		$this->mysql->begin();
		if (!$weixin->checkExits($wxid)) {
			$wxname = $weixinInfo['nickname'];
			$desc = $weixinInfo['desc'];

			$weixin->addWeixin($wxid, $wxname, $desc, $groupId, $__biz);
		}

		if ($this->api->checkWxidExists($wxid)) {
			exit('已被他人绑定');
		}
		
		$data['ppid'] = $_SESSION['ppid'];
		$data['wxid'] = $wxid;
		$time = time();
		$data['ctime'] = $time;
		$data['utime'] = $time;
		$this->mysql->insert('union_main', $data);
		$this->mysql->commit();
		echo 'add successfully';
	}

	public function __destruct(){
		if(!in_array(N_ACTION,$this->nohf)){
			n_mod('skin')->footer();
		}
	}
}